package sisi.enquires;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import sisi.General;
import sisi.agents.Agent;
import sisi.agents.AgentController;
import sisi.ports.Port;
import sisi.ports.PortController;
import sisi.yacht.Anayacht;
import sisi.yacht.AnayachtController;

/**
 * ReqshipfuelassignementWindow.java - Controller class for <i>reqshipfuelassignement window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 24/1/2014
 * 
 */

@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class ReqshipfuelassignementWindow extends Window implements 
				org.zkoss.zk.ui.ext.AfterCompose {
//window
private Window windowReqshipfuelassignement, windowEditReqshipfuelassignement;
private Textbox tbCerca;
private Listbox boxReqshipfuelassignement;
private List lista_Reqshipfuelassignement;
private boolean lNuovo;
private Toolbarbutton buttonSeleziona;
private ListModelList listModelList;
private Integer idSelezionato = 0;

protected Map<String, Object> args;
private Object ReqshipfuelassignementItem;
private Reqshipfuelassignement modReqshipfuelassignement;
// edit
private Textbox port;
private Textbox location;
private Intbox id;
private Intbox ref;
private Textbox agent;
private Textbox deliverytime;
private Textbox etatime;
private Textbox etdtime;
private Textbox lastport;
private Textbox nextport;
private Textbox country;
private Intbox portid;
private Textbox an;
private Textbox ba;
private Textbox buyer;
private Textbox cc1;
private Textbox cc2;
private Textbox cc3;
private Textbox cc4;
private Textbox delivery;
private Datebox dtdate;
private Textbox eta;
private Textbox etd;
private Textbox iq1;
private Textbox iq2;
private Textbox iq3;
private Textbox iq4;
private Textbox localphone;
private Textbox mds;
private Textbox qc1;
private Textbox qc2;
private Textbox qc3;
private Textbox qc4;
private Textbox sc1;
private Textbox sc2;
private Textbox sc3;
private Textbox sc4;
private Textbox specs;
private Textbox vessel;
private boolean idTrovato = true;
private Integer par_idport, par_idnextport, par_idlastport, par_idyacht, par_agentid;
private Date par_etadt, par_etddt, par_deliverydt, par_deliverytm, par_etatm, par_etdtm;
private String par_location;

		public void onCreate$windowReqshipfuelassignement(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		String tastoSeleziona = (String) args.get("tastoSeleziona");
		tastoSeleziona = (tastoSeleziona == null || tastoSeleziona.isEmpty() ? "N": tastoSeleziona);
		boolean lTastoSeleziona = tastoSeleziona.equals("S");
		if (!lTastoSeleziona) {
			buttonSeleziona.setVisible(false);
		}
		idSelezionato = (Integer) args.get("idselezionato");

		par_idport = (Integer) args.get("par_idport");
		par_idnextport = (Integer) args.get("par_idnextport");
		par_idlastport = (Integer) args.get("par_idlastport");
		par_idyacht = (Integer) args.get("par_idyacht");
		par_etadt = (Date) args.get("par_etadt");
		par_etatm = (Date) args.get("par_etatm");
		par_etddt = (Date) args.get("par_etddt");
		par_etdtm = (Date) args.get("par_etdtm");
		par_deliverydt = (Date) args.get("par_deliverydt");
		par_deliverytm = (Date) args.get("par_deliverytm");
		par_agentid = (Integer) args.get("par_agentid");
		par_location = (String) args.get("par_location");

		listModelList = new ListModelList();
		lista_Reqshipfuelassignement = new ReqshipfuelassignementController().getList(null);
		listModelList.addAll(lista_Reqshipfuelassignement);
		boxReqshipfuelassignement.setModel(listModelList);
		boxReqshipfuelassignement.setItemRenderer(new ReqshipfuelassignementItemRenderer());

		idTrovato = false;
		if (idSelezionato != null && idSelezionato != 0) {
			for (int i = 0; i < lista_Reqshipfuelassignement.size(); i++) {
				Reqshipfuelassignement record = (Reqshipfuelassignement) lista_Reqshipfuelassignement
						.get(i);
				if (record.getRef()!=null && record.getRef() == idSelezionato.intValue()) {
					boxReqshipfuelassignement.setSelectedIndex(i);
					idTrovato = true; 
					break;
				}
			}
			if (!idTrovato){
				// propongo inserimento nuovo record reqshipfuelassignement
				//Events.postEvent(new Event("onPippo", windowReqshipfuelassignement));
				Events.echoEvent(new Event("onNewAuto", windowReqshipfuelassignement)); 	
				//boxReqshipfuelassignement.
			}
		}


}
		
	public void onNewAuto$windowReqshipfuelassignement(Event event){
		if (!idTrovato){
			modifica(true);
		}
	}

	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);

	}

	public void onOK$tbCerca(Event event){
		cerca();
	}

	public void onClick$buttonCerca(Event event) {
		cerca();
	}


	private void cerca(){
		listModelList = new ListModelList();
		lista_Reqshipfuelassignement = new ReqshipfuelassignementController().getList(tbCerca.getValue());
		listModelList.addAll(lista_Reqshipfuelassignement);
		boxReqshipfuelassignement.setModel(listModelList);
		boxReqshipfuelassignement.setItemRenderer(new ReqshipfuelassignementItemRenderer());
	}

	public void onDoubleClicked(Event event) {
		if (buttonSeleziona.isVisible()) {
			seleziona();
		} else {
			modifica(false);
		}
	}

	public void onClick$buttonSeleziona(Event event) {

		seleziona();

}

	public void seleziona() {
		if (boxReqshipfuelassignement.getSelectedIndex() >= 0 && buttonSeleziona.isVisible()) {
			Object oReqshipfuelassignement = boxReqshipfuelassignement.getSelectedItem().getAttribute("rigaReqshipfuelassignement");
			String codiceSelezionato = ""+((Reqshipfuelassignement) oReqshipfuelassignement).getId();
			Sessions.getCurrent().setAttribute("codiceReqshipfuelassignementSelezionato", codiceSelezionato);
			windowReqshipfuelassignement.detach();
		}
	}

	public void onClick$buttonNuovo(Event event) {
		modifica(true);
	}

	public void onClick$buttonModifica(Event event) {
		modifica(false);
	}

	private void modifica(boolean nuovo){
		try {

			int nIndex = boxReqshipfuelassignement.getSelectedIndex();

			if (!nuovo && nIndex == -1) { // nessuna riga selezionata

				Messagebox.show("Selezionare una riga da modificare", "Information", Messagebox.OK, Messagebox.INFORMATION);

			} else {
				HashMap map = new HashMap();
				if (nuovo){
					map.put("lNuovo", true);
					map.put("idselezionato", idSelezionato);
					
					map.put("par_idport", par_idport);
					map.put("par_idnextport", par_idnextport);
					map.put("par_idlastport", par_idlastport);
					map.put("par_idyacht", par_idyacht);
					map.put("par_etadt", par_etadt);
					map.put("par_etatm", par_etatm);
					map.put("par_etddt", par_etddt);
					map.put("par_etdtm", par_etdtm);
					map.put("par_deliverydt", par_deliverydt);
					map.put("par_deliverytm", par_deliverytm);
					map.put("par_agentid", par_agentid);
					map.put("par_location", par_location);
				}
				map.put("boxReqshipfuelassignement", boxReqshipfuelassignement);
				Window finestraEditReqshipfuelassignement = (Window) Executions.createComponents("/editReqshipfuelassignement.zul", null, map);
				finestraEditReqshipfuelassignement.doModal();
			}

		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		}
	}

	public void onClick$buttonCancella(Event event) {
	// TODO Auto-generated method stub

	}
	
	/*
	public void onClick$buttonStampa(Event event) throws JRException, SQLException, IOException{

		
		int nIndex = boxReqshipfuelassignement.getSelectedIndex();

		if ( nIndex == -1) { // nessuna riga selezionata

			Messagebox.show("Selezionare una riga da modificare", "Information", Messagebox.OK, Messagebox.INFORMATION);
			return;

		} 
		
		Object oDetail = boxReqshipfuelassignement.getSelectedItem().getAttribute("rigaReqshipfuelassignement");
		Reqshipfuelassignement fa = (Reqshipfuelassignement) oDetail;
		
		
		String _utente = (String)Sessions.getCurrent().getAttribute("_utente"), _password = (String)Sessions.getCurrent().getAttribute("_password");
		
		String url = "jdbc:postgresql://localhost/pico";
		Properties props = new Properties();
		props.setProperty("user", _utente );
		props.setProperty("password", _password );
		Connection connection = DriverManager.getConnection(url, props);
		
		String nomeJrxml = new General().percorsoFincati()+"/ReqShipFuelAssignment.jrxml";
		//System.out.println(nomeJrxml);
		
		JasperReport report = JasperCompileManager.compileReport( nomeJrxml );

		// setup parameters for use with the report
		HashMap<String, Object> params = new HashMap<String,Object>();
		params.put( "ordine", fa.getRef() );

		// Fill the report data from the sql connection and parameters
		JasperPrint printedReport;
		printedReport = JasperFillManager.fillReport(report, params, connection);

		String outputFilename = new General().percorsoEsporta()+"/ReqShipFuelAssignement.pdf";
		//System.out.println(outputFilename);
		
		JasperExportManager.exportReportToPdfFile( printedReport, outputFilename );

		File file = new File(outputFilename);
		Filedownload.save(file, "PDF");


	}
	*/
	
	public void onClick$buttonStampa(Event event) throws JRException, SQLException, IOException{

		
		int nIndex = boxReqshipfuelassignement.getSelectedIndex();

		if ( nIndex == -1) { // nessuna riga selezionata

			Messagebox.show("Select a row to Print", "Information", Messagebox.OK, Messagebox.INFORMATION);
			return;

		} 
		
		Object oDetail = boxReqshipfuelassignement.getSelectedItem().getAttribute("rigaReqshipfuelassignement");
		Reqshipfuelassignement fa = (Reqshipfuelassignement) oDetail;

		
		String _utente = (String)Sessions.getCurrent().getAttribute("_utente"), _password = (String)Sessions.getCurrent().getAttribute("_password");
		
		String url = "jdbc:postgresql://localhost/pico";
		Properties props = new Properties();
		props.setProperty("user", _utente );
		props.setProperty("password", _password );
		Connection connection = DriverManager.getConnection(url, props);
		

		// setup parameters for use with the report
		HashMap<String, Object> params = new HashMap<String,Object>();
		params.put( "ordine", fa.getRef() );
		params.put( "PATH_IMG", new General().percorsoImg() + "/" );

		// Fill the report data from the sql connection and parameters
		JasperPrint printedReport;
		String fileJasper = new General().percorsoFincati()+"/ReqShipFuelAssignment.jasper";
		//System.out.println(fileJasper);
		
		printedReport = JasperFillManager.fillReport(fileJasper, params, connection);

		String outputFilename = new General().percorsoEsporta()+"/ReqShipFuelAssignement.pdf";
		//System.out.println(outputFilename);
		
		JasperExportManager.exportReportToPdfFile( printedReport, outputFilename );

		File file = new File(outputFilename);
		Filedownload.save(file, "PDF");


	}
	
	public class ReqshipfuelassignementItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			new Listcell(""+((Reqshipfuelassignement) data).getRef()).setParent(li);
			new Listcell(""+((Reqshipfuelassignement) data).getVessel()).setParent(li);
			li.setAttribute("rigaReqshipfuelassignement", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}


// EDIT: NEW/MODIFY
	public void onCreate$windowEditReqshipfuelassignement(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();

		boxReqshipfuelassignement = (Listbox) args.get("boxReqshipfuelassignement");
		idSelezionato = (Integer)args.get("idselezionato");
		
		par_idport = (Integer) args.get("par_idport");
		par_idnextport = (Integer) args.get("par_idnextport");
		par_idlastport = (Integer) args.get("par_idlastport");
		par_idyacht = (Integer) args.get("par_idyacht");
		par_etadt = (Date) args.get("par_etadt");
		par_etatm = (Date) args.get("par_etatm");
		par_etddt = (Date) args.get("par_etddt");
		par_etdtm = (Date) args.get("par_etdtm");
		par_deliverydt = (Date) args.get("par_deliverydt");
		par_deliverytm = (Date) args.get("par_deliverytm");
		par_agentid = (Integer) args.get("par_agentid");
		par_location = (String) args.get("par_location");

		if (args.containsKey("lNuovo")) {
			lNuovo = true;
		} else {
			lNuovo = false;
		}

		if (!lNuovo) {
			ReqshipfuelassignementItem = boxReqshipfuelassignement.getSelectedItem().getAttribute("rigaReqshipfuelassignement");
			modReqshipfuelassignement = new ReqshipfuelassignementController().refresh((Reqshipfuelassignement) ReqshipfuelassignementItem);
			ReqshipfuelassignementItem = modReqshipfuelassignement;
			windowEditReqshipfuelassignement.setTitle("Edit Reqshipfuelassignement");
			//categoryname.setFocus(true);
			//id.setValue(modCategorie.getCategoryid());
			//categoryname.setValue(modCategorie.getCategoryname());
			//description.setValue(modCategorie.getDescription());
			port.setValue(modReqshipfuelassignement.getPort());
			location.setValue(modReqshipfuelassignement.getLocation());
			id.setValue(modReqshipfuelassignement.getId());
			ref.setValue(modReqshipfuelassignement.getRef());
			agent.setValue(modReqshipfuelassignement.getAgent());
			deliverytime.setValue(modReqshipfuelassignement.getDeliverytime());
			etatime.setValue(modReqshipfuelassignement.getEtatime());
			etdtime.setValue(modReqshipfuelassignement.getEtdtime());
			lastport.setValue(modReqshipfuelassignement.getLastport());
			nextport.setValue(modReqshipfuelassignement.getNextport());			
			country.setValue(modReqshipfuelassignement.getCountry());
			portid.setValue(modReqshipfuelassignement.getPortid());
			an.setValue(modReqshipfuelassignement.getAn());
			ba.setValue(modReqshipfuelassignement.getBa());
			buyer.setValue(modReqshipfuelassignement.getBuyer());
			cc1.setValue(modReqshipfuelassignement.getCc1());
			cc2.setValue(modReqshipfuelassignement.getCc2());
			cc3.setValue(modReqshipfuelassignement.getCc3());
			cc4.setValue(modReqshipfuelassignement.getCc4());
			delivery.setValue(modReqshipfuelassignement.getDelivery());
			dtdate.setValue( (java.util.Date) (modReqshipfuelassignement.getDtdate()));
			eta.setValue(modReqshipfuelassignement.getEta());
			etd.setValue(modReqshipfuelassignement.getEtd());
			iq1.setValue(modReqshipfuelassignement.getIq1());
			iq2.setValue(modReqshipfuelassignement.getIq2());
			iq3.setValue(modReqshipfuelassignement.getIq3());
			iq4.setValue(modReqshipfuelassignement.getIq4());
			localphone.setValue(modReqshipfuelassignement.getLocalphone());
			mds.setValue(modReqshipfuelassignement.getMds());
			qc1.setValue(modReqshipfuelassignement.getQc1());
			qc2.setValue(modReqshipfuelassignement.getQc2());
			qc3.setValue(modReqshipfuelassignement.getQc3());
			qc4.setValue(modReqshipfuelassignement.getQc4());
			sc1.setValue(modReqshipfuelassignement.getSc1());
			sc2.setValue(modReqshipfuelassignement.getSc2());
			sc3.setValue(modReqshipfuelassignement.getSc3());
			sc4.setValue(modReqshipfuelassignement.getSc4());
			specs.setValue(modReqshipfuelassignement.getSpecs());
			vessel.setValue(modReqshipfuelassignement.getVessel());
		} else {
			windowEditReqshipfuelassignement.setTitle("New Reqshipfuelassignement");
			if (idSelezionato != null){
				ref.setValue(idSelezionato); 
				
				String portname = "";
				String parcountry = "";
				if (par_idport!=null){
					Port portref = new PortController().getPortxId(par_idport);
					portname = portref.getPortname();
					parcountry = portref.getCountry();
				}
				
				String vesselname = "";
				if (par_idyacht!=null){
					Anayacht yacht = new AnayachtController().getAnayachtxId(par_idyacht);
					if (yacht!=null){
						vesselname = yacht.getName();
					}
				}
				
				String agentCompanyName = "";
				if (par_agentid!=null && par_agentid.compareTo(0) > 0 ){
					Agent agente = new AgentController().getxId(par_agentid);
					agentCompanyName = agente.getCompanyname();
				}
				agent.setValue(agentCompanyName);
				
				vessel.setValue( vesselname );
				port.setValue( portname );
				country.setValue( parcountry );

				
				if (par_idlastport!=null){
					Port portlast = new PortController().getPortxId(par_idlastport);
					lastport.setValue(portlast.getPortname());					
				}

				if (par_idnextport!=null){
					Port portnext = new PortController().getPortxId(par_idnextport);
					nextport.setValue(portnext.getPortname());
				}			
				
				if (par_location!=null){
					location.setValue(par_location);
				}
				
				// eta, etatime, etd, etdtime, delivery, delivery time
				//par_deliverydt = (Date) args.get("par_deliverydt");
				//par_deliverytm = (Timestamp) args.get("par_deliverytm");
				if (par_etadt!=null){
					eta.setValue( General.formatoFecha(par_etadt) );
				}
				if (par_etatm!=null){
					etatime.setValue( General.formatoOra(par_etatm));
				}
				if (par_etddt!=null){
					etd.setValue( General.formatoFecha(par_etddt));
				}
				if (par_etdtm!=null){
					etdtime.setValue( General.formatoOra(par_etdtm));
				}
				if (par_deliverydt!=null){
					delivery.setValue( General.formatoFecha(par_deliverydt));
				}
				if (par_deliverytm!=null){
					deliverytime.setValue( General.formatoOra(par_deliverytm));
				}
				
			}
			//categoryname.setFocus(true);
		}

	}

	
	public void onClick$btnAnnulla(Event event){
		windowEditReqshipfuelassignement.detach();
	}
	


	public void onClick$btnConferma(Event event){
		if (lNuovo){
			modReqshipfuelassignement = new Reqshipfuelassignement();
		} else {

		}
		String testoMsg = "";

		modReqshipfuelassignement.setPort(port.getValue());
		modReqshipfuelassignement.setLocation(location.getValue());
		modReqshipfuelassignement.setId(id.getValue());
		modReqshipfuelassignement.setRef(ref.getValue());
		modReqshipfuelassignement.setAgent(agent.getValue());
		modReqshipfuelassignement.setDeliverytime(deliverytime.getValue());
		modReqshipfuelassignement.setEtatime(etatime.getValue());
		modReqshipfuelassignement.setEtdtime(etdtime.getValue());
		modReqshipfuelassignement.setLastport(lastport.getValue());
		modReqshipfuelassignement.setNextport(nextport.getValue());
		modReqshipfuelassignement.setCountry(country.getValue());
		modReqshipfuelassignement.setPortid(portid.getValue());
		modReqshipfuelassignement.setAn(an.getValue());
		modReqshipfuelassignement.setBa(ba.getValue());
		modReqshipfuelassignement.setBuyer(buyer.getValue());
		modReqshipfuelassignement.setCc1(cc1.getValue());
		modReqshipfuelassignement.setCc2(cc2.getValue());
		modReqshipfuelassignement.setCc3(cc3.getValue());
		modReqshipfuelassignement.setCc4(cc4.getValue());
		modReqshipfuelassignement.setDelivery(delivery.getValue());
		modReqshipfuelassignement.setDtdate( (dtdate.getValue() != null ? (java.sql.Date) sisi.General.date2Sql(dtdate.getValue()): null) );
		modReqshipfuelassignement.setEta(eta.getValue());
		modReqshipfuelassignement.setEtd(etd.getValue());
		modReqshipfuelassignement.setIq1(iq1.getValue());
		modReqshipfuelassignement.setIq2(iq2.getValue());
		modReqshipfuelassignement.setIq3(iq3.getValue());
		modReqshipfuelassignement.setIq4(iq4.getValue());
		modReqshipfuelassignement.setLocalphone(localphone.getValue());
		modReqshipfuelassignement.setMds(mds.getValue());
		modReqshipfuelassignement.setQc1(qc1.getValue());
		modReqshipfuelassignement.setQc2(qc2.getValue());
		modReqshipfuelassignement.setQc3(qc3.getValue());
		modReqshipfuelassignement.setQc4(qc4.getValue());
		modReqshipfuelassignement.setSc1(sc1.getValue());
		modReqshipfuelassignement.setSc2(sc2.getValue());
		modReqshipfuelassignement.setSc3(sc3.getValue());
		modReqshipfuelassignement.setSc4(sc4.getValue());
		modReqshipfuelassignement.setSpecs(specs.getValue());
		modReqshipfuelassignement.setVessel(vessel.getValue());

		if (lNuovo){
			new ReqshipfuelassignementController().add(modReqshipfuelassignement);
			testoMsg = "New Reqshipfuelassignement: "+ General.trimNull( modReqshipfuelassignement.getVessel() );
		} else {
			new ReqshipfuelassignementController().update(modReqshipfuelassignement);
			testoMsg = "Update Reqshipfuelassignement: "+ General.trimNull( modReqshipfuelassignement.getVessel() );
		}

		General.showNotify( testoMsg, windowEditReqshipfuelassignement);

		windowEditReqshipfuelassignement.detach();

		// aggiorna listbox

		if (lNuovo){
			ListModelList lml = (ListModelList) boxReqshipfuelassignement.getListModel();
			lml.add(modReqshipfuelassignement);
			boxReqshipfuelassignement.setSelectedIndex(lml.indexOf(modReqshipfuelassignement));
		} else {
			ListModelList lml = (ListModelList) boxReqshipfuelassignement.getListModel();
			Object oReqshipfuelassignementItem = boxReqshipfuelassignement.getSelectedItem().getAttribute("rigaReqshipfuelassignement");
			if (lml.indexOf(oReqshipfuelassignementItem) == -1) {
				// non trovato... quindi non lo aggiorno
			} else {
				lml.set(lml.indexOf(oReqshipfuelassignementItem), modReqshipfuelassignement);
			}
		}
	}

}
